<!DOCTYPE html>
<html lang="zh-cn">
<head>
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
  <title>Python变量可变性 - (power up)</title>
  <meta name="renderer" content="webkit" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>

<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />

<meta name="theme-color" content="#f8f5ec" />
<meta name="msapplication-navbutton-color" content="#f8f5ec">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="#f8f5ec">


<meta name="author" content="Kevin Jiang" /><meta name="description" content="Python变量的可变与不可变 Mutable and Immutable 可变是一种奇特的说法，即对象的内部状态已更改/突变。 所以，最简单的定义是：内部状态可以改变的对象是可变的" /><meta name="keywords" content="KevinJiang, AI大模型, AI落地, 全栈工程师, Java, Spring Boot" />






<meta name="generator" content="Hugo 0.84.4 with theme even" />


<link rel="canonical" href="http://kevinjiang.info/post/python/python%E5%8F%98%E9%87%8F%E5%8F%AF%E5%8F%98%E6%80%A7/" />
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/manifest.json">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">



<link href="/sass/main.min.78f8f17bab244b9ee62ad16480c9584d5fc2db06ae20681d1ca225cefd80767c.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.css" integrity="sha256-7TyXnr2YU040zfSP+rEcz29ggW4j56/ujTPwjMzyqFY=" crossorigin="anonymous">


<meta property="og:title" content="Python变量可变性" />
<meta property="og:description" content="Python变量的可变与不可变 Mutable and Immutable 可变是一种奇特的说法，即对象的内部状态已更改/突变。 所以，最简单的定义是：内部状态可以改变的对象是可变的" />
<meta property="og:type" content="article" />
<meta property="og:url" content="http://kevinjiang.info/post/python/python%E5%8F%98%E9%87%8F%E5%8F%AF%E5%8F%98%E6%80%A7/" /><meta property="article:section" content="post" />
<meta property="article:published_time" content="2022-11-13T18:13:19+08:00" />
<meta property="article:modified_time" content="2022-11-13T18:13:19+08:00" />

<meta itemprop="name" content="Python变量可变性">
<meta itemprop="description" content="Python变量的可变与不可变 Mutable and Immutable 可变是一种奇特的说法，即对象的内部状态已更改/突变。 所以，最简单的定义是：内部状态可以改变的对象是可变的"><meta itemprop="datePublished" content="2022-11-13T18:13:19+08:00" />
<meta itemprop="dateModified" content="2022-11-13T18:13:19+08:00" />
<meta itemprop="wordCount" content="2605">
<meta itemprop="keywords" content="Python," /><meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="Python变量可变性"/>
<meta name="twitter:description" content="Python变量的可变与不可变 Mutable and Immutable 可变是一种奇特的说法，即对象的内部状态已更改/突变。 所以，最简单的定义是：内部状态可以改变的对象是可变的"/>

<!--[if lte IE 9]>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/classlist/1.1.20170427/classList.min.js"></script>
<![endif]-->

<!--[if lt IE 9]>
  <script src="https://cdn.jsdelivr.net/npm/html5shiv@3.7.3/dist/html5shiv.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/respond.js@1.4.2/dest/respond.min.js"></script>
<![endif]-->

</head>
<body>
  <div id="mobile-navbar" class="mobile-navbar">
  <div class="mobile-header-logo">
    <a href="/" class="logo">(Power up)</a>
  </div>
  <div class="mobile-navbar-icon">
    <span></span>
    <span></span>
    <span></span>
  </div>
</div>
<nav id="mobile-menu" class="mobile-menu slideout-menu">
  <ul class="mobile-menu-list">
    <a href="/">
        <li class="mobile-menu-item">首页</li>
      </a><a href="/post/">
        <li class="mobile-menu-item">归档</li>
      </a><a href="/tags/">
        <li class="mobile-menu-item">标签</li>
      </a><a href="/categories/">
        <li class="mobile-menu-item">分类</li>
      </a><a href="/resume/">
        <li class="mobile-menu-item">简历</li>
      </a>
  </ul>

  


</nav>

  <div class="container" id="mobile-panel">
    <header id="header" class="header">
        <div class="logo-wrapper">
  <a href="/" class="logo">(Power up)</a>
</div>





<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
        <a class="menu-item-link" href="/">首页</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/post/">归档</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/tags/">标签</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/categories/">分类</a>
      </li><li class="menu-item">
        <a class="menu-item-link" href="/resume/">简历</a>
      </li>
  </ul>
</nav>

    </header>

    <main id="main" class="main">
      <div class="content-wrapper">
        <div id="content" class="content">
          <article class="post">
    
    <header class="post-header">
      <h1 class="post-title">Python变量可变性</h1>

      <div class="post-meta">
        <span class="post-time"> 2022-11-13 </span>
        
          <span class="more-meta"> 约 2605 字 </span>
          <span class="more-meta"> 预计阅读 6 分钟 </span>
        
      </div>
    </header>

    <div class="post-toc" id="post-toc">
  <h2 class="post-toc-title">文章目录</h2>
  <div class="post-toc-content always-active">
    <nav id="TableOfContents">
  <ul>
    <li><a href="#可变定义">可变定义</a></li>
    <li><a href="#不可变定义">不可变定义</a></li>
    <li><a href="#可变和不可变对象列表">可变和不可变对象列表</a></li>
    <li><a href="#python-中的对象">Python 中的对象</a>
      <ul>
        <li><a href="#python中的可变对象">Python中的可变对象</a></li>
        <li><a href="#python中的不可变对象">Python中的不可变对象</a></li>
      </ul>
    </li>
  </ul>
</nav>
  </div>
</div>
    <div class="post-content">
      <p>Python变量的可变与不可变</p>
<p><strong><strong>Mutable and Immutable</strong></strong></p>
<p>可变是一种奇特的说法，即对象的内部状态已更改/突变。 所以，最简单的定义是：内部状态可以改变的对象是可变的。 另一方面，不可变对象一旦创建就不允许对其进行任何更改。这两种状态都是 Python 数据结构的组成部分。</p>
<h2 id="可变定义">可变定义</h2>
<p>可变是指某些东西是可变的或有能力改变的。 在 Python 中“可变”是对象改变其值的能力。这些通常是存储数据集合的对象。</p>
<h2 id="不可变定义">不可变定义</h2>
<p>不可变是指随着时间的推移不可能发生变化。 在 Python 中，如果一个对象的值不能随时间改变，那么它就是不可变的。一旦创建，这些对象的值是永久固定的，直到被回收。</p>
<h2 id="可变和不可变对象列表">可变和不可变对象列表</h2>
<p>内置可变类型：</p>
<ul>
<li>列表（List）</li>
<li>集合（Set）</li>
<li>字典（Dictionarie）</li>
<li>自定义类（User-Defined Classes 取决于用户的定义）</li>
</ul>
<p>内置不可变类型：</p>
<ul>
<li>数字 （Integer, Rational, Float, Decimal, Complex &amp; Booleans）</li>
<li>字符串（String）</li>
<li>元组（Tuple）</li>
<li>冻结的集合（Frozen Set）</li>
<li>自定义类（User-Defined Classes 取决于用户的定义）</li>
</ul>
<p>对象可变性是使 Python 成为动态类型语言的特征之一。尽管 Python 中的 Mutable 和 Immutable 是一个非常基本的概念，但由于不变性的不传递性，它有时会让人有些困惑。</p>
<h2 id="python-中的对象">Python 中的对象</h2>
<p>在 Python 中，一切都被视为对象。 每个对象都具有以下三个属性：</p>
<p>Identity — 这是指对象在计算机内存中引用的地址，使用<a href="https://docs.python.org/3/library/functions.html?highlight=id#id">id</a>函数可以得到唯一标识。
Type — 这是指创建的对象的类型。 例如：整数、列表、字符串等。
Value — 这是指对象存储的值。 例如：List=[1,2,3] 将保存数字 1,2 和 3
虽然 ID 和 Type 一经创建就无法更改，但 Mutable 对象的值可以更改。</p>
<h3 id="python中的可变对象">Python中的可变对象</h3>
<p>与其深入研究 Python 中可变和不可变的理论方面，不如用简单的代码来描述它在 Python 中的含义。</p>
<p>让我们逐步讨论以下代码：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="c1"># 创建一个包含城市名称的列表</span>
<span class="n">cities</span> <span class="o">=</span> <span class="p">[</span><span class="s1">&#39;Shanghai&#39;</span><span class="p">,</span> <span class="s1">&#39;Changsha&#39;</span><span class="p">,</span> <span class="s1">&#39;Guangzhou&#39;</span><span class="p">]</span>

<span class="k">for</span> <span class="n">city</span> <span class="ow">in</span> <span class="n">cities</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">city</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39;, &#39;</span><span class="p">)</span>

<span class="c1"># 输出: Shanghai, Changsha, Guangzhou,</span>
</code></pre></td></tr></table>
</div>
</div><p>以十六进制格式打印内存地址中创建的对象的位置</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="nb">print</span><span class="p">(</span><span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">cities</span><span class="p">)))</span>

<span class="c1"># 输出: 0x185bd166100</span>
<span class="c1"># 输出内容会根据不同的机器，不同的运行环境，结果也不相同</span>
</code></pre></td></tr></table>
</div>
</div><p>添加一个新的城市到列表当中</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">cities</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="s1">&#39;Shenzheng&#39;</span><span class="p">)</span>
<span class="k">for</span> <span class="n">city</span> <span class="ow">in</span> <span class="n">cities</span><span class="p">:</span>
    <span class="nb">print</span><span class="p">(</span><span class="n">city</span><span class="p">,</span> <span class="n">end</span><span class="o">=</span><span class="s1">&#39;, &#39;</span><span class="p">)</span>

<span class="nb">print</span><span class="p">(</span><span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">cities</span><span class="p">)))</span>

<span class="c1"># 输出: Changsha, Guangzhou, Shenzheng,  0x185bd166100</span>
</code></pre></td></tr></table>
</div>
</div><p>可以看到，最后输出的十六进制的地址是没有改变的。</p>
<p>上面的例子告诉我们，我们可以通过再添加一个城市”Shenzheng”来改变对象“cities”的内部状态，但是对象的内存地址并没有改变。这证实了我们没有创建一个新对象，而是同一个对象被更改或变异了。因此，我们可以说具有引用变量名称“城市”的列表类型的对象是 Mutable object。</p>
<p>现在让我们讨论 Immutable一词。考虑到我们理解 mutable 的含义，很明显 immutable 的定义将包含“不”。这是不可变的最简单定义 —— 内部状态不能改变的对象是不可变的。</p>
<h3 id="python中的不可变对象">Python中的不可变对象</h3>
<p>同样的，一个简单的代码将是描述不可变代表什么的最佳方式。 因此，让我们逐步讨论以下代码：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span><span class="lnt">11
</span><span class="lnt">12
</span><span class="lnt">13
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="c1"># 创建一个包含每周工作日名称的元组</span>
<span class="n">weekdays</span> <span class="o">=</span> <span class="s1">&#39;Sunday&#39;</span><span class="p">,</span> <span class="s1">&#39;Monday&#39;</span><span class="p">,</span> <span class="s1">&#39;Tuesday&#39;</span><span class="p">,</span> <span class="s1">&#39;Wednesday&#39;</span><span class="p">,</span> <span class="s1">&#39;Thursday&#39;</span><span class="p">,</span> <span class="s1">&#39;Friday&#39;</span><span class="p">,</span> <span class="s1">&#39;Saturday&#39;</span>

<span class="c1">## 打印工作日名称元组</span>
<span class="nb">print</span><span class="p">(</span><span class="n">weekdays</span><span class="p">)</span>

<span class="c1"># 输出: (&#39;Sunday&#39;, &#39;Monday&#39;, &#39;Tuesday&#39;, &#39;Wednesday&#39;, &#39;Thursday&#39;, &#39;Friday&#39;, &#39;Saturday&#39;)</span>

<span class="c1"># 打印十六进制格式内存地址</span>

<span class="nb">print</span><span class="p">(</span><span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">weekdays</span><span class="p">)))</span>

<span class="c1"># 输出: 0x241fa15fa60</span>
</code></pre></td></tr></table>
</div>
</div><p>元组是不可变的，因此不能添加新元素。</p>
<p>使用带有 <code>+=</code> 运算符的元组合并在元组“weekdays”中添加新的元素</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">weekdays</span> <span class="o">+=</span> <span class="p">(</span><span class="s1">&#39;Pythonday&#39;</span><span class="p">,)</span>

<span class="nb">print</span><span class="p">(</span><span class="n">weekdays</span><span class="p">)</span>

<span class="nb">print</span><span class="p">(</span><span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">weekdays</span><span class="p">)))</span>

<span class="c1"># 输出：</span>
<span class="c1"># (&#39;Sunday&#39;, &#39;Monday&#39;, &#39;Tuesday&#39;, &#39;Wednesday&#39;, &#39;Thursday&#39;, &#39;Friday&#39;, &#39;Saturday&#39;, &#39;Pythonday&#39;)</span>
<span class="c1"># 0x22d51ba9a50</span>
</code></pre></td></tr></table>
</div>
</div><p>上面的例子表明我们能够使用相同的变量名来引用一个对象，该对象是一种包含七个元素的元组。 但是，新旧元组的 ID 或内存位置并不相同。 我们无法更改对象“weekdays”的内部状态。Python 程序管理器在内存地址中创建了一个新对象，变量名称“weekdays”开始引用包含八个元素的新对象。 因此，我们可以说具有引用变量名称“weekdays”的元组类型的对象是 Immutable object。</p>
<p>那么如何使用可变和不可变对象：</p>
<p>可变对象可用于您希望允许任何更新的地方。 例如，您有一个组织中的员工姓名列表，每次雇用新成员时都需要更新该列表。 您可以创建一个可变列表，并且可以轻松更新它。</p>
<p>不变性为我们在允许并行处理的以网络为中心的环境中执行的不同敏感任务提供了许多有用的应用程序。 通过创建不可变对象，您可以密封值并确保没有线程可以调用对数据的覆盖/更新。 这在您想要编写一段无法修改的代码的情况下也很有用。 例如，尝试查找不可变对象的值的调试代码。</p>
<p>注意不变性的非传递性：</p>
<p>好的！ 现在我们确实了解了 Python 中的可变对象和不可变对象是什么。 让我们继续讨论这两者的结合并探索可能性。 让我们讨论一下，如果您有一个包含可变对象的不可变对象，它将如何表现？ 或相反亦然？ 让我们再次使用代码来理解这种行为</p>
<p>创建一个元组（不可变对象），包含两个列表（可变对象）：</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="c1"># 列表表示名字，年龄和性别</span>
<span class="n">persons</span> <span class="o">=</span> <span class="p">([</span><span class="s1">&#39;Aron&#39;</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="s1">&#39;Male&#39;</span><span class="p">],</span> <span class="p">[</span><span class="s1">&#39;Anusha&#39;</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="s1">&#39;Female&#39;</span><span class="p">])</span>
<span class="c1"># 打印元组</span>
<span class="nb">print</span><span class="p">(</span><span class="n">persons</span><span class="p">)</span>
<span class="c1"># 打印十六进制内存地址</span>
<span class="nb">print</span><span class="p">(</span><span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">persons</span><span class="p">)))</span>

<span class="c1"># 输出：</span>
<span class="c1"># ([&#39;Aron&#39;, 5, &#39;Male&#39;], [&#39;Anusha&#39;, 8, &#39;Female&#39;])</span>
<span class="c1"># 0x16eb651cb40</span>
</code></pre></td></tr></table>
</div>
</div><p>更改第一个元素的年龄，使用索引 <code>[0]</code> 选择元组的第一个元素，然后使用索引 <code>[1]</code> 选择列表的第二个元素并将年龄的值赋值为4</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt">1
</span><span class="lnt">2
</span><span class="lnt">3
</span><span class="lnt">4
</span><span class="lnt">5
</span><span class="lnt">6
</span><span class="lnt">7
</span><span class="lnt">8
</span><span class="lnt">9
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="n">persons</span><span class="p">[</span><span class="mi">0</span><span class="p">][</span><span class="mi">1</span><span class="p">]</span> <span class="o">=</span> <span class="mi">4</span>
<span class="c1"># 打印更新后的元组</span>
<span class="nb">print</span><span class="p">(</span><span class="n">persons</span><span class="p">)</span>
<span class="c1"># 打印十六进制内存地址</span>
<span class="nb">print</span><span class="p">(</span><span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">persons</span><span class="p">)))</span>

<span class="c1"># 输出：</span>
<span class="c1"># ([&#39;Aron&#39;, 4, &#39;Male&#39;], [&#39;Anusha&#39;, 8, &#39;Female&#39;])</span>
<span class="c1"># 0x16eb651cb40</span>
</code></pre></td></tr></table>
</div>
</div><p>在上面的代码中，您可以看到对象“persons”是不可变的，内存地址没有改变，因为它是一种元组。但是，它有两个列表作为元素，我们可以更改列表的状态（列表是可变的）。所以，这里我们并没有改变 Tuple 内部的对象引用，而是被引用的对象发生了变异。</p>
<p>同样地，让我们探讨一下如果你有一个包含不可变对象的可变对象，它将如何表现？ 让我们再次使用代码来理解行为</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="c1"># 创建一个包含两个元组的列表对象</span>
<span class="n">list1</span> <span class="o">=</span> <span class="p">[(</span><span class="mi">1</span><span class="p">,</span> <span class="mi">2</span><span class="p">,</span> <span class="mi">3</span><span class="p">),</span> <span class="p">(</span><span class="mi">4</span><span class="p">,</span> <span class="mi">5</span><span class="p">,</span> <span class="mi">6</span><span class="p">)]</span>
<span class="c1"># 打印</span>
<span class="nb">print</span><span class="p">(</span><span class="n">list1</span><span class="p">)</span>
<span class="c1"># 打印内存地址</span>
<span class="nb">print</span><span class="p">(</span><span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">list1</span><span class="p">)),</span> <span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">list1</span><span class="p">[</span><span class="mi">0</span><span class="p">])),</span> <span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">list1</span><span class="p">[</span><span class="mi">1</span><span class="p">])))</span>

<span class="c1"># 输出：</span>
<span class="c1"># [(1, 2, 3), (4, 5, 6)]</span>
<span class="c1"># 0x1b355326080 0x1b35539b900 0x1b3555fc1c0</span>
</code></pre></td></tr></table>
</div>
</div><p>列表的元素是可以修改，但是列表里面的元组元素修改是不被允许的。</p>
<div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="c1"># 修改列表的第一个元素值</span>
<span class="n">list1</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">=</span> <span class="p">(</span><span class="mi">7</span><span class="p">,</span> <span class="mi">8</span><span class="p">,</span> <span class="mi">9</span><span class="p">)</span>
<span class="c1"># 打印列表</span>
<span class="nb">print</span><span class="p">(</span><span class="n">list1</span><span class="p">)</span>
<span class="c1"># 打印内存地址</span>
<span class="nb">print</span><span class="p">(</span><span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">list1</span><span class="p">)),</span> <span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">list1</span><span class="p">[</span><span class="mi">0</span><span class="p">])),</span> <span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">list1</span><span class="p">[</span><span class="mi">1</span><span class="p">])))</span>

<span class="c1"># 输出：</span>
<span class="c1"># [(7, 8, 9), (4, 5, 6)]</span>
<span class="c1"># 0x1b355326080 0x1b3553261c0 0x1b3555fc1c0</span>
</code></pre></td></tr></table>
</div>
</div><div class="highlight"><div class="chroma">
<table class="lntable"><tr><td class="lntd">
<pre class="chroma"><code><span class="lnt"> 1
</span><span class="lnt"> 2
</span><span class="lnt"> 3
</span><span class="lnt"> 4
</span><span class="lnt"> 5
</span><span class="lnt"> 6
</span><span class="lnt"> 7
</span><span class="lnt"> 8
</span><span class="lnt"> 9
</span><span class="lnt">10
</span></code></pre></td>
<td class="lntd">
<pre class="chroma"><code class="language-python" data-lang="python"><span class="c1"># 把列表的第二个元素，也就是第二个元组拼接上一个新的值</span>
<span class="n">list1</span><span class="p">[</span><span class="mi">1</span><span class="p">]</span> <span class="o">+=</span> <span class="p">(</span><span class="mi">3</span><span class="p">,)</span>
<span class="c1"># 打印列表</span>
<span class="nb">print</span><span class="p">(</span><span class="n">list1</span><span class="p">)</span>
<span class="c1"># 打印内存地址</span>
<span class="nb">print</span><span class="p">(</span><span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">list1</span><span class="p">)),</span> <span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">list1</span><span class="p">[</span><span class="mi">0</span><span class="p">])),</span> <span class="nb">hex</span><span class="p">(</span><span class="nb">id</span><span class="p">(</span><span class="n">list1</span><span class="p">[</span><span class="mi">1</span><span class="p">])))</span>

<span class="c1"># 输出：</span>
<span class="c1"># [(7, 8, 9), (4, 5, 6, 3)]</span>
<span class="c1"># 0x1b355326080 0x1b3553261c0 0x1b355513540</span>
</code></pre></td></tr></table>
</div>
</div><p>从上面两段程序的结果来看，list1的内存地址是没有改变的，改变列表里面的整个元素的值，也不会改变那个元素的内存地址，啥时内存里面的内容发生了改变。而对一个不可变元素进行扩展的时候，内存地址是发生了改变的。</p>
<p><strong>元组的不变性</strong></p>
<p>元组是不可变的，因此一旦在 Python 中创建，它们就不能有任何更改。 这是因为它们支持与字符串相同的序列操作。 我们都知道字符串是不可变的。 索引运算符将从元组中选择一个元素，就像在字符串中一样。 因此，它们是不可变的。</p>

    </div>

    <div class="post-copyright">
  <p class="copyright-item">
    <span class="item-title">文章作者</span>
    <span class="item-content">Kevin Jiang</span>
  </p>
  <p class="copyright-item">
    <span class="item-title">上次更新</span>
    <span class="item-content">
        2022-11-13
        
    </span>
  </p>
  
  <p class="copyright-item">
    <span class="item-title">许可协议</span>
    <span class="item-content"><a rel="license noopener" href="https://creativecommons.org/licenses/by-nc-nd/4.0/" target="_blank">CC BY-NC-ND 4.0</a></span>
  </p>
</div>
<div class="post-reward">
  <input type="checkbox" name="reward" id="reward" hidden />
  <label class="reward-button" for="reward">赞赏支持</label>
  <div class="qr-code">
    
    <label class="qr-code-image" for="reward">
        <img class="image" src="/img/wechat_pay_1242x1242.jpg">
        <span>微信打赏</span>
      </label>
    <label class="qr-code-image" for="reward">
        <img class="image" src="/img/alipay_600x600.jpg">
        <span>支付宝打赏</span>
      </label>
  </div>
</div><footer class="post-footer">
      <div class="post-tags">
          <a href="/tags/python/">Python</a>
          </div>
      <nav class="post-nav">
        <a class="prev" href="/post/linux/%E4%BF%9D%E6%8C%81ssh%E4%BC%9A%E8%AF%9D%E5%9C%A8%E7%BA%BF/">
            <i class="iconfont icon-left"></i>
            <span class="prev-text nav-default">保持SSH会话在线</span>
            <span class="prev-text nav-mobile">上一篇</span>
          </a>
        <a class="next" href="/post/cloudnative/docker%E4%BF%AE%E6%94%B9%E6%97%B6%E5%8C%BA/">
            <span class="next-text nav-default">Docker修改时区</span>
            <span class="next-text nav-mobile">下一篇</span>
            <i class="iconfont icon-right"></i>
          </a>
      </nav>
    </footer>
  </article>
        </div>
        

  

  

      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="social-links">
      <a href="mailto:wenlin1988@126.com" class="iconfont icon-email" title="email"></a>
      <a href="https://www.linkedin.com/in/%E6%96%87%E6%9E%97-%E8%92%8B-0a3204126/" class="iconfont icon-linkedin" title="linkedin"></a>
      <a href="https://github.com/kevindragon" class="iconfont icon-github" title="github"></a>
  <a href="http://kevinjiang.info/index.xml" type="application/rss+xml" class="iconfont icon-rss" title="rss"></a>
</div>

<div class="copyright">
  <span class="power-by">
    由 <a class="hexo-link" href="https://gohugo.io">Hugo</a> 强力驱动
  </span>
  <span class="division">|</span>
  <span class="theme-info">
    主题 -
    <a class="theme-link" href="https://github.com/olOwOlo/hugo-theme-even">Even</a>
  </span>

  

  <span class="copyright-year">
    &copy;
    2015 -
    2023<span class="heart"><i class="iconfont icon-heart"></i></span><span>Kevin Jiang</span>
    <a href="https://beian.miit.gov.cn/" target="_blank">湘ICP备2022022745号</a>
  </span>
</div>

    </footer>

    <div class="back-to-top" id="back-to-top">
      <i class="iconfont icon-up"></i>
    </div>
  </div>
  
  <script src="https://cdn.jsdelivr.net/npm/jquery@3.2.1/dist/jquery.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/slideout@1.0.1/dist/slideout.min.js" integrity="sha256-t+zJ/g8/KXIJMjSVQdnibt4dlaDxc9zXr/9oNPeWqdg=" crossorigin="anonymous"></script>
  <script src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3.1.20/dist/jquery.fancybox.min.js" integrity="sha256-XVLffZaxoWfGUEbdzuLi7pwaUJv1cecsQJQqGLe7axY=" crossorigin="anonymous"></script>



<script type="text/javascript" src="/js/main.min.c99b103c33d1539acf3025e1913697534542c4a5aa5af0ccc20475ed2863603b.js"></script>
  <script type="text/javascript">
    window.MathJax = {
      tex: {
        inlineMath: [['$','$'], ['\\(','\\)']],
        tags: 'ams',
        }
    };
  </script>
  <script type="text/javascript" async src="/lib/mathjax/es5/tex-mml-chtml.js"></script>

<script id="baidu_analytics">
  var _hmt = _hmt || [];
  (function() {
    if (window.location.hostname === 'localhost') return;
    var hm = document.createElement("script"); hm.async = true;
    hm.src = "https://hm.baidu.com/hm.js?b73ff6d4afc4af9e582d8a5dc068bab9";
    var s = document.getElementsByTagName("script")[0];
    s.parentNode.insertBefore(hm, s);
  })();
</script>






</body>
</html>
